<!-- 日报/周报/月报生成 -->
<template>
  <div class="pdca-report">
    <button-group :btn-group="btnGroup" style="margin-bottom: 10px;" @paste-click="handlePaste" @submit-click="handleSubmit" @renew-click="getNewReport" @draft-click="isShowDraft = !isShowDraft" />
    <div class="input-board">
      <el-input
        v-model="reportInfo.content"
        type="textarea"
        rows="30"
        placeholder="请输入内容"
      />
      <el-input
        v-if="isShowDraft"
        v-model="draft"
        type="textarea"
        rows="30"
      />
    </div>
  </div>
</template>

<script>
export default {
  props: {
    // 项目id
    projectId: {
      type: Number,
      default: -1
    },
    // 选项
    options: {
      type: Object,
      default: () => {}
    },
    // 类型
    mark: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      reportInfo: {},
      draft: '',
      isShowDraft: false,
      btnGroup: [
        { type: 'primary', text: '复制', action: 'paste' },
        { type: 'success', text: '打卡', action: 'submit' },
        { type: 'warning', text: '重新生成日报', action: 'renew' },
        { type: 'info', text: '草稿', action: 'draft' }
      ]
    }
  },
  created() {
    this.initData()
  },
  methods: {
    async initData() {
      let params = {}
      switch (this.mark) {
        case 'daily':
          params = {
            type: 'daily',
            project_id: this.projectId,
            year: new Date().getFullYear() + '',
            month: new Date().getMonth() + 1 + '',
            date: new Date().getDate() + ''
          }
          break
        case 'month':
          params = {
            type: 'month',
            project_id: this.projectId,
            year: new Date().getFullYear() + '',
            month: new Date().getMonth() + 1 + ''
          }
          break
        default:
          break
      }
      const { data } = await this.$http.report.list(params)
      if (data.length) {
        this.reportInfo = data[0]
      } else {
        // 重新生成日报
        this.getNewReport()
      }
    },
    // 重新生成日报
    async getNewReport() {
      switch (this.mark) {
        case 'daily': {
          const tmp = new Date()
          tmp.setTime(tmp.getTime())
          const startOn = tmp.getFullYear() + '-' + (tmp.getMonth() + 1) + '-' + tmp.getDate()
          const tmp2 = new Date()
          tmp2.setTime(tmp2.getTime() + 24 * 60 * 60 * 1000)
          const finishOn = tmp2.getFullYear() + '-' + (tmp2.getMonth() + 1) + '-' + tmp2.getDate()
          const params = {
            project_id: this.projectId,
            start_on: new Date(startOn),
            finish_on: new Date(finishOn)
          }
          const { data: list } = await this.$http.pdca.getReport(params)
          const result = [`${startOn} 日报`]
          list.forEach((item, index) => {
            result.push(`${index + 1}.【${item.type_name}】${item.content} 100%`)
          })
          const project_name = this.projectId ? this.options.projectList.find(item => item.id === this.projectId).value : null
          const info = {
            id: this.reportInfo.id || null,
            year: new Date().getFullYear() + '',
            month: new Date().getMonth() + 1 + '',
            date: new Date().getDate() + '',
            type: 'daily',
            type_name: '日报',
            project_id: this.projectId,
            project_name,
            content: result.join('\n')
          }
          this.reportInfo = info
          break
        }
        case 'month': {
          // 获取本月第一天以及下个月第一天
          const now = new Date()
          const startOn = new Date(now.getFullYear(), now.getMonth(), 1)
          const nextMonth = now.getMonth() === 11 ? 0 : now.getMonth() + 1
          const finishOn = nextMonth !== 0 ? new Date(now.getFullYear(), nextMonth, 1) : new Date(now.getFullYear() + 1, 0, 1)
          // 请求接口
          const params = {
            project_id: this.projectId,
            start_on: new Date(startOn),
            finish_on: new Date(finishOn)
          }
          const { data: list } = await this.$http.pdca.getReport(params)
          const startOnString = startOn.getFullYear() + '年' + (startOn.getMonth() + 1) + '月'
          const result = [`${startOnString}月报`]
          list.forEach((item, index) => {
            result.push(`${index + 1}.【${item.type_name}】${item.content}`)
          })
          const project_name = this.projectId ? this.options.projectList.find(item => item.id === this.projectId).value : null
          const info = {
            id: this.reportInfo.id || null,
            year: new Date().getFullYear() + '',
            month: new Date().getMonth() + 1 + '',
            type: 'month',
            type_name: '月报',
            project_id: this.projectId,
            project_name,
            content: result.join('\n')
          }
          this.reportInfo = info
          break
        }
      }
    },
    // 打卡
    handleSubmit() {
      const params = JSON.parse(JSON.stringify(this.reportInfo))
      if (!params.id) delete params.id
      this.$http.report.addOrUpdate(params).then(() => {
        this.$message.success('打卡成功')
        this.$emit('handleClose')
      })
    },
    // 复制
    handlePaste() {
      if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(this.reportInfo.content).then(() => {
          this.$message.success('复制成功')
        })
      } else {
        // 创建text area
        const textArea = document.createElement('textarea')
        textArea.value = this.reportInfo.content
        // 使text area不在viewport，同时设置不可见
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()
        this.$message.success('复制成功')
        return new Promise((res, rej) => {
          // 执行复制命令并移除文本框
          document.execCommand('copy') ? res() : rej()
          textArea.remove()
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.pdca-report {
  padding: 10px;
}
.input-board {
  display: flex;
}
</style>
